<template>
  <div class="admin-page">
    <div class="page-header">
      <h1 class="page-title">日程管理</h1>
      <p class="page-subtitle">管理系统中的所有日程</p>
    </div>
    
    <el-card class="content-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span class="card-title">日程列表</span>
          <div class="header-actions">
            <el-button type="primary" @click="openCreateDialog" style="margin-right: 8px">新增日程</el-button>
            <el-input v-model="creatorId" placeholder="按创建人ID过滤" style="width: 220px" />
            <el-button type="primary" @click="load()" style="margin-left: 8px">查询</el-button>
            <el-button @click="exportCSV('schedules.csv', ['scheduleId','title','status','priority'])" style="margin-left: 8px">导出CSV</el-button>
          </div>
        </div>
      </template>
    <el-table :data="pagedData" v-loading="loading" @sort-change="onSortChange" :default-sort="{ prop: 'scheduleId', order: 'ascending' }">
      <el-table-column prop="scheduleId" label="#" width="80" />
      <el-table-column prop="title" label="标题" sortable="custom" v-if="isColVisible('title')" />
      <el-table-column prop="status" label="状态" width="120" sortable="custom" v-if="isColVisible('status')" />
      <el-table-column prop="priority" label="优先级" width="120" sortable="custom" v-if="isColVisible('priority')" />
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button link type="primary" @click="$router.push(`/schedule/${row.scheduleId}`)">详情</el-button>
          <el-button link type="warning" @click="editSchedule(row)">修改</el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="暂无数据">
        </el-empty>
      </template>
    </el-table>
    <div style="margin-top:12px; display:flex; justify-content:flex-end">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        v-model:current-page="page"
        v-model:page-size="pageSize"
        :page-sizes="[10,20,50,100]"
        @current-change="(v)=>page=v"
        @size-change="(v)=>pageSize=v"
      />
    </div>
  </el-card>
  
  <!-- 修改日程对话框 -->
  <el-dialog v-model="editDialogVisible" title="修改日程" width="600px">
    <el-form :model="editForm" label-width="100px" ref="editFormRef">
      <el-form-item label="标题" prop="title" :rules="[{ required: true, message: '请输入标题' }]">
        <el-input v-model="editForm.title" placeholder="请输入日程标题" />
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <el-input v-model="editForm.content" type="textarea" :rows="3" placeholder="请输入日程内容" />
      </el-form-item>
      <el-form-item label="开始时间" prop="startTime" :rules="[{ required: true, message: '请选择开始时间' }]">
        <el-date-picker
          v-model="editForm.startTime"
          type="datetime"
          placeholder="选择开始时间"
          format="YYYY-MM-DD HH:mm"
          value-format="YYYY-MM-DD HH:mm"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime" :rules="[{ required: true, message: '请选择结束时间' }]">
        <el-date-picker
          v-model="editForm.endTime"
          type="datetime"
          placeholder="选择结束时间"
          format="YYYY-MM-DD HH:mm"
          value-format="YYYY-MM-DD HH:mm"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="地点" prop="location">
        <el-input v-model="editForm.location" placeholder="请输入地点" />
      </el-form-item>
      <el-form-item label="优先级" prop="priority">
        <el-select v-model="editForm.priority" placeholder="请选择优先级" style="width: 100%">
          <el-option label="低" value="low" />
          <el-option label="中" value="medium" />
          <el-option label="高" value="high" />
        </el-select>
      </el-form-item>
      <el-form-item label="提醒时间" prop="remindTime">
        <el-date-picker
          v-model="editForm.remindTime"
          type="datetime"
          placeholder="选择提醒时间（可选）"
          format="YYYY-MM-DD HH:mm"
          value-format="YYYY-MM-DD HH:mm"
          style="width: 100%"
          clearable
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveSchedule" :loading="saving">保存</el-button>
      </span>
    </template>
  </el-dialog>
  
  <!-- 新增日程对话框 -->
  <el-dialog v-model="createDialogVisible" title="新增日程" width="600px">
    <el-form :model="createForm" label-width="100px" ref="createFormRef">
      <el-form-item label="标题" prop="title" :rules="[{ required: true, message: '请输入标题' }]">
        <el-input v-model="createForm.title" placeholder="请输入日程标题" />
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <el-input v-model="createForm.content" type="textarea" :rows="3" placeholder="请输入日程内容" />
      </el-form-item>
      <el-form-item label="开始时间" prop="startTime" :rules="[{ required: true, message: '请选择开始时间' }]">
        <el-date-picker
          v-model="createForm.startTime"
          type="datetime"
          placeholder="选择开始时间"
          format="YYYY-MM-DD HH:mm"
          value-format="YYYY-MM-DD HH:mm"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime" :rules="[{ required: true, message: '请选择结束时间' }]">
        <el-date-picker
          v-model="createForm.endTime"
          type="datetime"
          placeholder="选择结束时间"
          format="YYYY-MM-DD HH:mm"
          value-format="YYYY-MM-DD HH:mm"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="地点" prop="location">
        <el-input v-model="createForm.location" placeholder="请输入地点" />
      </el-form-item>
      <el-form-item label="优先级" prop="priority">
        <el-select v-model="createForm.priority" placeholder="请选择优先级" style="width: 100%">
          <el-option label="低" value="low" />
          <el-option label="中" value="medium" />
          <el-option label="高" value="high" />
        </el-select>
      </el-form-item>
      <el-form-item label="提醒时间" prop="remindTime">
        <el-date-picker
          v-model="createForm.remindTime"
          type="datetime"
          placeholder="选择提醒时间（可选）"
          format="YYYY-MM-DD HH:mm"
          value-format="YYYY-MM-DD HH:mm"
          style="width: 100%"
          clearable
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="createDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="createSchedule" :loading="creating">创建</el-button>
      </span>
    </template>
  </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { api } from '@/utils/api'
import { useTable } from '@/composables/useTable'

const { data, setData, loading, total, page, pageSize, pagedData, onSortChange, isColVisible, exportCSV } = useTable({ pageSize: 10, defaultVisible: ['title','status','priority'] })
const creatorId = ref('')

// 修改日程相关
const editDialogVisible = ref(false)
const editFormRef = ref()
const saving = ref(false)
const editForm = ref({
  scheduleId: null,
  creatorId: null,
  title: '',
  content: '',
  startTime: '',
  endTime: '',
  location: '',
  priority: 'medium',
  remindTime: ''
})

// 新增日程相关
const createDialogVisible = ref(false)
const createFormRef = ref()
const creating = ref(false)
const createForm = ref({
  title: '',
  content: '',
  startTime: '',
  endTime: '',
  location: '',
  priority: 'medium',
  remindTime: ''
})

async function load() {
  loading.value = true
  try {
    const params = new URLSearchParams()
    if (creatorId.value) params.set('creatorId', creatorId.value)
    const resp = await api.get(`/api/schedule${params.toString() ? `?${params}` : ''}`)
    if (resp && Array.isArray(resp.records)) setData(resp.records, resp.total)
    else if (Array.isArray(resp)) setData(resp)
    else setData([])
    page.value = 1
  } finally {
    loading.value = false
  }
}

// 编辑日程函数
function editSchedule(row) {
  editForm.value = {
    scheduleId: row.scheduleId,
    creatorId: row.creatorId,
    title: row.title || '',
    content: row.content || '',
    startTime: row.startTime || '',
    endTime: row.endTime || '',
    location: row.location || '',
    priority: row.priority || 'medium',
    remindTime: row.remindTime || ''
  }
  editDialogVisible.value = true
}

// 保存日程函数
async function saveSchedule() {
  if (!editForm.value.title) {
    ElMessage.error('请输入日程标题')
    return
  }
  
  saving.value = true
  try {
    const uid = localStorage.getItem('userId')
    
    // 格式化时间为后端要求的格式 yyyy-MM-dd HH:mm
    const formatDateTime = (date) => {
      if (!date) return null
      const d = new Date(date)
      const year = d.getFullYear()
      const month = String(d.getMonth() + 1).padStart(2, '0')
      const day = String(d.getDate()).padStart(2, '0')
      const hours = String(d.getHours()).padStart(2, '0')
      const minutes = String(d.getMinutes()).padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}`
    }
    
    const updateData = {
      title: editForm.value.title,
      content: editForm.value.content,
      startTime: formatDateTime(editForm.value.startTime),
      endTime: formatDateTime(editForm.value.endTime),
      location: editForm.value.location,
      priority: editForm.value.priority,
      remindTime: formatDateTime(editForm.value.remindTime),
      creatorId: parseInt(uid)
    }
    
    console.log('发送更新数据:', updateData)
    
    // 使用项目的api工具进行API调用
    const result = await api.post(`/api/schedule/${editForm.value.scheduleId}/update`, updateData)
    console.log('更新响应:', result)
    
    ElMessage.success('日程修改成功')
    editDialogVisible.value = false
    await load() // 重新加载数据
  } catch (error) {
    console.error('保存日程失败:', error)
    ElMessage.error('保存失败，请重试')
  } finally {
    saving.value = false
  }
}

// 打开新增对话框
function openCreateDialog() {
  // 重置表单
  createForm.value = {
    title: '',
    content: '',
    startTime: '',
    endTime: '',
    location: '',
    priority: 'medium',
    remindTime: ''
  }
  createDialogVisible.value = true
}

// 创建日程函数
async function createSchedule() {
  if (!createForm.value.title) {
    ElMessage.error('请输入日程标题')
    return
  }
  
  if (!createForm.value.startTime) {
    ElMessage.error('请选择开始时间')
    return
  }
  
  if (!createForm.value.endTime) {
    ElMessage.error('请选择结束时间')
    return
  }
  
  creating.value = true
  try {
    const uid = localStorage.getItem('userId')
    
    // 格式化时间为后端要求的格式 yyyy-MM-dd HH:mm
    const formatDateTime = (date) => {
      if (!date) return null
      const d = new Date(date)
      const year = d.getFullYear()
      const month = String(d.getMonth() + 1).padStart(2, '0')
      const day = String(d.getDate()).padStart(2, '0')
      const hours = String(d.getHours()).padStart(2, '0')
      const minutes = String(d.getMinutes()).padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}`
    }
    
    const scheduleData = {
      title: createForm.value.title,
      content: createForm.value.content,
      startTime: formatDateTime(createForm.value.startTime),
      endTime: formatDateTime(createForm.value.endTime),
      location: createForm.value.location,
      priority: createForm.value.priority,
      remindTime: formatDateTime(createForm.value.remindTime),
      creatorId: parseInt(uid)
    }
    
    console.log('发送创建数据:', scheduleData)
    
    // 使用项目的api工具进行API调用
    const result = await api.post('/api/schedule', scheduleData)
    console.log('创建响应:', result)
    
    ElMessage.success('日程创建成功')
    createDialogVisible.value = false
    await load() // 重新加载数据
  } catch (error) {
    console.error('创建日程失败:', error)
    ElMessage.error('创建失败，请重试')
  } finally {
    creating.value = false
  }
}

onMounted(load)
</script>

<style scoped>
.admin-page {
  padding: 24px;
  background: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 24px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
  margin: 0 0 8px 0;
}

.page-subtitle {
  font-size: 14px;
  color: #6b7280;
  margin: 0;
}

.content-card {
  border-radius: 12px;
  border: 1px solid #e5e7eb;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #374151;
}

.header-actions {
  display: flex;
  align-items: center;
}

:deep(.el-card__header) {
  padding: 20px 24px;
  border-bottom: 1px solid #f3f4f6;
  background: #fafbfc;
}

:deep(.el-card__body) {
  padding: 24px;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background: #f8fafc;
  color: #374151;
  font-weight: 600;
}

:deep(.el-table td) {
  border-bottom: 1px solid #f3f4f6;
}

:deep(.el-table tr:hover > td) {
  background: #f8fafc;
}

:deep(.el-pagination) {
  justify-content: flex-end;
}
</style>

<style scoped>
.actions { margin-bottom: 12px; display: flex; gap: 8px; }
</style>
